#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: oss_old.py
# @time: 2021/3/3 19:05
# @desc:
import os

import boto3
# import oss2

# from .aws import s3, AWS_S3_BUCKET_NAME
from utils.aws import s3, AWS_S3_BUCKET_NAME, AWS_S3_SECRET_ACCESS_KEY, AWS_S3_ACCESS_KEY_ID

# 阿里云部分
ACCESS_KEY_ID_1 = "LTAI4Fy5ASruP9bbcCFrxutK"
ACCESS_KEY_SECRET_1 = "Ag9wilvaUWBALVMm0J8e6lqG8qmNss"

ACCESS_KEY_ID_2 = "Ag9wilvaUWBALVMm0J8e6lqG8qmNss"
ACCESS_KEY_SECRET_2 = "fiGPtuhUuos3Q9ohBiGqVZtjjRLSYw"

# 地域节点
ENDPOINT = "oss-cn-shanghai.aliyuncs.com"

# 桶名
BUCKET_NAME = "designorder"
# auth = oss2.Auth(ACCESS_KEY_ID_1, ACCESS_KEY_SECRET_1)
# bucket = oss2.Bucket(auth, ENDPOINT, BUCKET_NAME)


def download_file_from_oss(
        oss_file_name: str,
        local_file_name: str = None,
) -> str:
    """
    把服务器上的文件下载到本地，需要添加逻辑判断要下载的图片是否在oss上。

    :param oss_file_name: oss上的文件路径名
    :param local_file_name: 本地文件路径名
    """
    if local_file_name is None:
        local_file_name = oss_file_name

    try:
        object_stream = bucket.get_object(oss_file_name)
    except:
        return f"文件{oss_file_name}下载发生问题，请检查文件名是否正确"
    local_file_folder = os.path.dirname(local_file_name)
    if not os.path.exists(local_file_folder):
        os.makedirs(local_file_folder)
    with open(local_file_name, 'wb') as f:
        f.write(object_stream.read())

    return f"文件{oss_file_name}成功下载到{local_file_name}"


def upload_file_to_oss(
        local_file_name: str,
        oss_file_name: str = None,
        oss_file_dirname: str = "DODesign_Dev/pythonfiles",
) -> str:
    """
    从本地向服务器上传文件的函数

    :param local_file_name: 本地文件路径名
    :param oss_file_name: oss上的文件名
    :param oss_file_dirname: oss上的文件路径
    """
    if oss_file_name is None:
        oss_file_name = local_file_name
    print(f"{oss_file_dirname}/{oss_file_name}")
    result = bucket.put_object_from_file(f"{oss_file_dirname}/{oss_file_name}", local_file_name)
    # result = bucket.put_object_from_file(os.path.join(oss_file_dirname, oss_file_name), local_file_name)
    if result.status == 200:
        return f"文件{local_file_name}成功上传为{oss_file_name}"
    else:
        return f"文件{local_file_name}上传失败"


def delete_file_on_oss(
        oss_file_name: str,
):
    try:
        bucket.delete_object(oss_file_name)
    except:
        return f"文件{oss_file_name}删除失败，这个文件可能不存在。"
    return f"文件{oss_file_name}成功删除。"


# 亚马逊云部分
def download_file_from_oss(
        oss_file_name: str,
        local_file_name: str = None,
) -> str:
    """
    把服务器上的文件下载到本地，需要添加逻辑判断要下载的图片是否在oss上。

    :param oss_file_name: oss上的文件路径名
    :param local_file_name: 本地文件路径名
    """
    if local_file_name is None:
        local_file_name = oss_file_name
    local_file_folder = os.path.dirname(local_file_name)
    if not os.path.exists(local_file_folder):
        os.makedirs(local_file_folder)
    try:
        s3.download_file(oss_file_name, local_file_name)
        return f"文件{oss_file_name}成功下载到{local_file_name}"
    except:
        return f"文件{oss_file_name}下载发生问题，请检查文件名是否正确"


def upload_file_to_oss(
        local_file_name: str,
        oss_file_name: str = None,
        oss_file_dirname: str = "DOCenter_Dev/Pythonfiles",
) -> str:
    """
    从本地向服务器上传文件的函数

    :param local_file_name: 本地文件路径名
    :param oss_file_name: oss上的文件名
    :param oss_file_dirname: oss上的文件路径
    """
    if oss_file_name is None:
        oss_file_name = local_file_name
    print(f"{oss_file_dirname}/{oss_file_name}")

    data = open(local_file_name, 'rb')
    try:
        s3.upload_file(
            upload_path=f"{oss_file_dirname}/{oss_file_name}",
            data=data,
        )
        return f"文件{local_file_name}成功上传为{oss_file_name}"
    except:
        return f"文件{local_file_name}上传失败"


def OSS_file_is_exist(
        oss_file_name: str,
        oss_file_dirname: str = "DOCenter_Dev/Pythonfiles",
):
    s3 = boto3.resource(
        's3',
        aws_access_key_id=AWS_S3_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_S3_SECRET_ACCESS_KEY,
    )
    bucket = s3.Bucket(AWS_S3_BUCKET_NAME)
    for obj in bucket.objects.filter(Prefix=f"{oss_file_dirname}/{oss_file_name}"):
        print(obj)
    #     if obj.key == file_name:
    #         return True
    # return False

# import os
# path = r"infuck.json"
# print(r"do_design_automatic_assembly/infuck.json")
# upload_file_to_oss(path)

if __name__ == '__main__':
    # OSS_file_is_exist("temp/standard_part/2021040000001002.stl")
    # for i in s3.get_all_key("designorder"):
    #     print(i)
    import os
    path = r"do_design_automatic_assembly/infuck.json"
    print(r"do_design_automatic_assembly/infuck.json")
    upload_file_to_oss(path)